<?php
/*
 +----------------------------------------------------------------------
 + Title        : WebApiException 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/8/8 11:25
 + Last-time    : 2019/8/8 11:25+ 86187
 + Desc         : WebApiException
 +----------------------------------------------------------------------
*/


namespace app\http\exception;


use app\admin\service\NodeService;
use app\api\service\Token;
use library\tools\Node;
use think\Request;
use think\Response;

/**
 * 前端接口
 * Class WebApiException
 *
 * @package app\common\lib\exception
 */
class WebAdminApiException extends \think\exception\HttpResponseException
{
    protected $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }

    public function getResponse()
    {
//        $this->log();
        return $this->response;
    }

    public function log()
    {
        if(\think\facade\Request::isOptions()){
            return true;
        }
        $node = Node::current();

        $action = $this->getNodeName($node);
        $content = \think\facade\Request::method();
        $auth = \think\facade\Request::header('authorization');
        $user = '';
        if($users =  (new Token())->check($auth)){
            $user = $users->user->username.'['.$users->user->id.']';
        }
        $data = [
            'node'        => $node,
            'geoip'       => \PHP_SAPI === 'cli' ? '127.0.0.1' : request()->ip(),
            'action'      => $action,
            'content'     => $content,
            'username'    => $user,
            'request'     => json_encode(\request()->param(), JSON_UNESCAPED_UNICODE),
            'response'    => json_encode($this->response->getData(), JSON_UNESCAPED_UNICODE),
            'request_at'  => get_microtime_format(\think\facade\Request::time(true)),
            'response_at' => get_microtime_format(microtime(true))
        ];
        try {
            db('SystemLog')->insert($data);
        } catch (\Exception $e) {
            $e->getMessage();
        }
        return true;
    }

    public function getNodeName($node, $update = false)
    {
        $nodes = NodeService::getAuthList();
        return isset($nodes[$node]) ? $nodes[$node] : $node;
    }
}